from django.shortcuts import render, render_to_response

# Create your views here.


from .models import *

from django.http import Http404

from .forms import CommentForm  #导入评论表单

def get_blog(request):
    blogs = Blog.objects.all().order_by('-pub') # 获得所有的博客按时间倒序排列
    return render_to_response('blog_list.html', {'blog': blogs})

def get_details(request, blog_id): #获取对应博客的详细内容
    try:
        blog = Blog.objects.get(id=blog_id) # 获取对应博客
    except Blog.DoesNotExist:
        raise Http404

    if request.method == 'GET':   #如果用户是查询信息， 那么就是查询的表单内容
        form = CommentForm()
    else:  # 如果用户是提交内容
        form = CommentForm(request.POST)

        if form.is_valid():
            cleaned_date = form.cleaned_data
            cleaned_date['blog'] = blog
            Comment.objects.create(**cleaned_date)
    ctx = {
        'blog': blog,
        'comments': blog.comment_set.all().order_by('-pub'),
        'form': form
    }

    return render(request, 'blog_details.html', ctx)

